function gamaM = GamaM_2(mm,x);
% GAMA_M_2.M       Version I.K. - 22/12/06
%   This function is used by the objective function OBJ_FCT_GMM_MULTI_2
% COMMENTS:
%   GamaM_2.m uses the global variables ERROR_SERIES and INSTRUMENTS. Notation: Hamilton, ch 14.
 
global P ERROR_SERIES INSTRUMENTS;

T = size(ERROR_SERIES,1);
N = size(ERROR_SERIES,2);
p = P;
alpha = x(1:(N));
tau = 2*alpha - 1;

% Computing the gradient N x T matrix of the multivariate loss L(p,alpha,e) wrt e
norm_p = (sum((abs(ERROR_SERIES)).^(p*ones(T,N)),2)).^(1/p*ones(T,1));
norm_p_pm1 = norm_p.^((p-1)*ones(T,1));
nu_p = [];
for i=1:1:N
    nu_p = [nu_p, (sign(ERROR_SERIES(:,i))).*(abs(ERROR_SERIES(:,i)).^(p-1))];
end
grad_p = p*nu_p + norm_p_pm1*(tau')+(((p-1)*ERROR_SERIES*tau./norm_p)*ones(1,N)).*nu_p;

% Computing the vector function h1(x,Vt) 
h1 = [];
for i=(mm+1):1:T
    h1 = [h1; kron(grad_p(i,:),INSTRUMENTS(i,:))];   
end
% Computing the vector function h2(x,Vt) 
h2 = [];
for i=1:1:(T-mm)
    h2 = [h2; kron(grad_p(i,:),INSTRUMENTS(i,:))];   
end
% Computing gammaM
r1 = size(h1,1);
r2 = size(h2,1); 
if (r1~=r2)
    'Error: r1 ne r2 in the computation of gama_m!'
    stop;
end
% computing gamaM according to eq 14.1.20
gamaM = h1'*h2/T;
% gamaM = 0;
% j = 1;
% while j <= r1       % computing gamaM according to eq 14.1.20
%     % Now at j out off r1
% %     j 
%     gamaM = gamaM + h1(j,:)'*h2(j,:);
%     j = j+1;
% end
% gamaM = gamaM/T;
if (size(gamaM,1)~=size(h1,2))|(size(gamaM,2)~=size(h1,2))
    stop;
end
